package com.hua.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hua.handler.Result;
import com.hua.pojo.Collection;
import com.hua.pojo.Novel;
import com.hua.service.CollectionService;
import com.hua.service.NovelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/collection")
public class CollectionController {

    @Resource
    private CollectionService collectionService;
    @Autowired
    private NovelService novelService;

    //新增一条收藏数据
    @PostMapping("/addCollection")
    public Result<?> addCollection(@RequestBody Collection collection) {
        collectionService.save(collection);
        return Result.success();
    }

    //根据收藏id删除数据
    @DeleteMapping("/deleteCollection/{collectionId}")
    public Result<?> deleteCollection(@PathVariable String collectionId){
        boolean b = collectionService.removeById(collectionId);
        return Result.success(b);
    }


    //根据小说id查询该条收藏id
    @PostMapping("/selectGetOneCollection/{novelId}")
    public Result<?> selectGetOneCollection(@PathVariable String novelId) {
        LambdaQueryWrapper<Collection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collection::getNovelId, novelId);
        Collection one = collectionService.getOne(wrapper);
        return Result.success(one.getCollectionId());
    }
    //根据小说id查询收藏数据
    @PostMapping("/selectCollection")
    public Result<?> selectCollection(@RequestBody Collection collection) {
        LambdaQueryWrapper<Collection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collection::getNovelId, collection.getNovelId()).eq(Collection::getUserId,collection.getUserId());
        Collection one = collectionService.getOne(wrapper);
        if (one == null){
            return Result.error("404","错误");
        }
        return Result.success(one);
    }

    //根据用户id查询小说id集合
    @PostMapping("/selectNovelIds/{userId}")
    public Result<?> selectNovelIds(@PathVariable String userId){
        ArrayList<Novel> novelArrayList = new ArrayList<>();
        LambdaQueryWrapper<Collection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collection::getUserId,userId);
        List<Collection> list = collectionService.list(wrapper);
        list.forEach(item -> {
            Novel novel = novelService.selectNovelData(item.getNovelId());
            novelArrayList.add(novel);
        });
        return Result.success(novelArrayList);
    }
}
